﻿
using OrBitDataModule.Base;
using OrBitDataModule.Interface;
using OrBitDataModule.Models;
using OrBitDataModule.UI.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OrBitDataModule.Common
{
    public static class ProtocolUtils
    {
        /// <summary>
        /// 获取任务对象
        /// </summary>
        /// <param name="namespaceName">默认值"OrBitDataModule.Protocol"</param>
        /// <param name="protocolType"></param>
        /// <param name="context"></param>
        /// <param name="uniqueId"></param>
        /// <param name="configJson"></param>
        /// <param name="taskName"></param>
        /// <param name="apiName"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static DataTaskBase CreatProtocol(string namespaceName, string protocolType, string uniqueId, string dataProtocolScriptId, string configJson, string taskName, string apiName, string username, string password)
        {
            Assembly assembly = Assembly.GetAssembly(typeof(DataTaskBase));
            var typesInNamespace = assembly.GetTypes().Where(t => t.Namespace == namespaceName);

            var handlerTypes = typesInNamespace.Where(type => typeof(DataTaskBase).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract);

            foreach (var handlerType in handlerTypes)
            {
                var attribute = handlerType.GetCustomAttributes(typeof(ProtocolTypeAttribute), true);
                if ((attribute == null) || (attribute.Length <= 0)) break;
                foreach (ProtocolTypeAttribute att in attribute)
                {
                    if (att.ProtocolType.Equals(protocolType))
                    {
                        DataTaskBase handler = (DataTaskBase)System.Activator.CreateInstance(handlerType, uniqueId, dataProtocolScriptId, configJson, taskName, protocolType, apiName, username, password);
                        return handler;
                    }
                }
            }
            return null;
        }
    }
}
